document.addEventListener('DOMContentLoaded', function () {
    createStars();
});
// 创建星空背景
function createStars() {
    const starsContainer = document.createElement('div');
    starsContainer.className = 'stars';
    document.body.appendChild(starsContainer);

    // 创建星星
    for (let i = 0; i < 200; i++) {
        const star = document.createElement('div');
        star.className = 'star';

        // 随机大小
        const size = Math.random() * 3;
        star.style.width = `${size}px`;
        star.style.height = `${size}px`;

        // 随机位置
        star.style.left = `${Math.random() * 100}%`;
        star.style.top = `${Math.random() * 100}%`;

        // 随机动画延迟
        star.style.setProperty('--duration', `${2 + Math.random() * 3}s`);
        star.style.setProperty('--delay', `${Math.random() * 5}s`);

        starsContainer.appendChild(star);
    }

    // 创建流星
    setInterval(() => {
        const shootingStar = document.createElement('div');
        shootingStar.className = 'shooting-star';

        // 随机起始位置
        shootingStar.style.left = `${Math.random() * 100}%`;
        shootingStar.style.top = `${Math.random() * 50}%`;

        // 随机动画延迟
        shootingStar.style.setProperty('--duration', `${1 + Math.random() * 2}s`);
        shootingStar.style.setProperty('--delay', `${Math.random() * 5}s`);

        starsContainer.appendChild(shootingStar);

        // 动画结束后移除流星
        setTimeout(() => {
            shootingStar.remove();
        }, 3000);
    }, 2000);
}

// 表单验证函数
function validatePhone(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
}

function validatePassword(password) {
    return password.length >= 6;
}

// 获取DOM元素
const loginForm = document.getElementById('loginForm');
const registerForm = document.getElementById('registerForm');
const tabBtns = document.querySelectorAll('.tab-btn');
const phonenumberInput = document.getElementById('phonenumber');
const passwordInput = document.getElementById('password');
const regUsernameInput = document.getElementById('regUsername');
const regGenderSelect = document.getElementById('regGender');
const regPhoneInput = document.getElementById('regPhone');
const regPasswordInput = document.getElementById('regPassword');
const regConfirmPasswordInput = document.getElementById('regConfirmPassword');

// 表单切换功能
tabBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        // 移除所有按钮的active类
        tabBtns.forEach(b => b.classList.remove('active'));
        // 添加当前按钮的active类
        btn.classList.add('active');

        // 切换表单显示
        const formType = btn.getAttribute('data-form');
        if (formType === 'login') {
            loginForm.classList.add('active');
            registerForm.classList.remove('active');
        } else {
            loginForm.classList.remove('active');
            registerForm.classList.add('active');
        }

        // 清空错误提示和输入框内容（可选，根据需求）
        clearAllErrors();
        resetForms();
    });
});

// 实时验证辅助函数
function showError(inputElement, message) {
    const errorDiv = inputElement.nextElementSibling;
    if (errorDiv) {
        errorDiv.textContent = message;
    }
}

function clearError(inputElement) {
    const errorDiv = inputElement.nextElementSibling;
    if (errorDiv) {
        errorDiv.textContent = '';
    }
}

// 清空所有错误提示
function clearAllErrors() {
    document.querySelectorAll('.error-message').forEach(el => el.textContent = '');
}

// 重置表单内容
function resetForms() {
    loginForm.reset();
    registerForm.reset();
}

// 实时验证登录表单
phonenumberInput.addEventListener('input', () => {
    if (phonenumberInput.value.trim() === '') {
        clearError(phonenumberInput);
    } else if (!validatePhone(phonenumberInput.value)) {
        showError(phonenumberInput, '请输入有效的手机号码');
    } else {
        clearError(phonenumberInput);
    }
});

passwordInput.addEventListener('input', () => {
    if (passwordInput.value.trim() === '') {
        clearError(passwordInput);
    } else if (!validatePassword(passwordInput.value)) {
        showError(passwordInput, '密码长度至少为6位');
    } else {
        clearError(passwordInput);
    }
});

// 实时验证注册表单
regUsernameInput.addEventListener('input', () => {
    if (regUsernameInput.value.trim() === '') {
        clearError(regUsernameInput);
    } else if (regUsernameInput.value.length < 2) {
        showError(regUsernameInput, '用户名至少需要2个字符');
    } else {
        clearError(regUsernameInput);
    }
});

regGenderSelect.addEventListener('change', () => {
    if (regGenderSelect.value === '') {
        clearError(regGenderSelect);
    } else {
        clearError(regGenderSelect);
    }
});

regPhoneInput.addEventListener('input', () => {
    if (regPhoneInput.value.trim() === '') {
        clearError(regPhoneInput);
    } else if (!validatePhone(regPhoneInput.value)) {
        showError(regPhoneInput, '请输入有效的手机号码');
    } else {
        clearError(regPhoneInput);
    }
});

regPasswordInput.addEventListener('input', () => {
    if (regPasswordInput.value.trim() === '') {
        clearError(regPasswordInput);
    } else if (!validatePassword(regPasswordInput.value)) {
        showError(regPasswordInput, '密码长度至少为6位');
    } else {
        clearError(regPasswordInput);
    }
});

regConfirmPasswordInput.addEventListener('input', () => {
    if (regConfirmPasswordInput.value.trim() === '') {
        clearError(regConfirmPasswordInput);
    } else if (regConfirmPasswordInput.value !== regPasswordInput.value) {
        showError(regConfirmPasswordInput, '两次输入的密码不一致');
    } else {
        clearError(regConfirmPasswordInput);
    }
});

// 登录表单提交处理
loginForm.addEventListener('submit', async (e) => {
    e.preventDefault();

    const phone = phonenumberInput.value.trim();
    const password = passwordInput.value.trim();
    const remember = document.getElementById('remember').checked;

    // 表单验证
    let hasError = false;

    if (phone === '') {
        showError(phonenumberInput, '请输入手机号码');
        hasError = true;
    } else if (!validatePhone(phone)) {
        showError(phonenumberInput, '请输入有效的手机号码');
        hasError = true;
    } else {
        clearError(phonenumberInput);
    }

    if (password === '') {
        showError(passwordInput, '请输入密码');
        hasError = true;
    } else if (!validatePassword(password)) {
        showError(passwordInput, '密码长度至少为6位');
        hasError = true;
    } else {
        clearError(passwordInput);
    }

    if (hasError) return;

    // 禁用按钮并显示加载状态
    const loginBtn = loginForm.querySelector('button[type="submit"]');
    loginBtn.disabled = true;
    loginBtn.classList.add('loading');
    try {
        $.ajax({
            url: 'http://localhost:8080/user/login',
            type: 'POST',
            contentType: 'application/x-www-form-urlencoded',
            data: { phone, password },
            success: function (response) {
                // console.log(response.data);
                
                if (response.data) {
                    // 保存token和用户信息
                    localStorage.setItem('token', response.data);
                    localStorage.setItem('userId', response.data.split(':')[1]);
                    if (response.user) {
                        localStorage.setItem('userInfo', JSON.stringify(response.user));
                    }
                    window.location.href = '/index-ai.html';
                } else {
                    alert(response.message || '登录失败，请检查账号密码');
                }
            },
            error: function (xhr, status, error) {
                console.error('登录失败:', error, xhr.responseText);
                let errorMsg = '登录失败，请稍后重试';
                if (status === 'timeout') {
                    errorMsg = '请求超时，请检查网络';
                } else if (xhr.status === 401) {
                    errorMsg = '账号或密码错误';
                }
                try {
                    const errorResponse = JSON.parse(xhr.responseText);
                    alert(errorResponse.message || errorMsg);
                } catch (e) {
                    alert(errorMsg);
                }
            },
            complete: function () {
                // 恢复按钮状态
                loginBtn.disabled = false;
                loginBtn.classList.remove('loading');
            }
        });

    } catch (error) {
        console.error('登录请求异常:', error);
        alert('登录失败，请稍后重试');
        // 恢复按钮状态
        loginBtn.disabled = false;
        loginBtn.classList.remove('loading');
    }
});

// 注册表单提交处理
registerForm.addEventListener('submit', async (e) => {
    e.preventDefault();

    const userName = regUsernameInput.value.trim();
    const sex = regGenderSelect.value;
    const phone = regPhoneInput.value.trim();
    const password = regPasswordInput.value.trim();
    const confirmPassword = regConfirmPasswordInput.value.trim();

    // 表单验证
    let hasError = false;

    if (userName === '') {
        showError(regUsernameInput, '请输入用户名');
        hasError = true;
    } else if (userName.length < 2) {
        showError(regUsernameInput, '用户名至少需要2个字符');
        hasError = true;
    } else {
        clearError(regUsernameInput);
    }

    if (sex === '') {
        showError(regGenderSelect, '请选择性别');
        hasError = true;
    } else {
        clearError(regGenderSelect);
    }

    if (phone === '') {
        showError(regPhoneInput, '请输入手机号码');
        hasError = true;
    } else if (!validatePhone(phone)) {
        showError(regPhoneInput, '请输入有效的手机号码');
        hasError = true;
    } else {
        clearError(regPhoneInput);
    }

    if (password === '') {
        showError(regPasswordInput, '请输入密码');
        hasError = true;
    } else if (!validatePassword(password)) {
        showError(regPasswordInput, '密码长度至少为6位');
        hasError = true;
    } else {
        clearError(regPasswordInput);
    }

    if (confirmPassword === '') {
        showError(regConfirmPasswordInput, '请确认密码');
        hasError = true;
    } else if (confirmPassword !== password) {
        showError(regConfirmPasswordInput, '两次输入的密码不一致');
        hasError = true;
    } else {
        clearError(regConfirmPasswordInput);
    }

    if (hasError) return;

    // 禁用按钮并显示加载状态
    const registerBtn = registerForm.querySelector('button[type="submit"]');
    registerBtn.disabled = true;
    registerBtn.classList.add('loading');

    try {
        // 使用 jQuery AJAX 进行注册请求
        $.ajax({
            url: 'http://localhost:8080/user/register',
            type: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify({
                userName,
                sex,    
                phone,
                password
            }),
            success: function (response) {
                if(response.code !== 200){
                    alert(response.message);
                }
                alert('注册成功！请登录');
                // 切换到登录表单
                document.querySelector('[data-form="login"]').click();
                // 清空注册表单
                registerForm.reset();
                // 清空所有错误提示
                registerForm.querySelectorAll('.error-message').forEach(el => el.textContent = '');
                console.log(response);
                

            },
            error: function (xhr, status, error) {
                console.error('注册失败:', error, xhr.responseText);
                try {
                    const errorResponse = JSON.parse(xhr.responseText);
                    alert(errorResponse.message || '注册失败，请稍后重试');
                } catch (e) {
                    alert('注册失败，请稍后重试');
                }
            },
            complete: function () {
                // 恢复按钮状态
                registerBtn.disabled = false;
                registerBtn.classList.remove('loading');
            }
        });

    } catch (error) {
        console.error('注册请求异常:', error);
        alert('注册失败，请稍后重试');
        // 恢复按钮状态
        registerBtn.disabled = false;
        registerBtn.classList.remove('loading');
    }
});

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    // 默认显示登录表单（如果需要）
    // document.querySelector('[data-form="login"]').click(); 
});